import config from '@/config/cache'

class Cache {

  /**
   * 设置缓存
   * @param {string} key 缓存标识
   * @param {any} value	存储数据
   * @param {null|number|Date} expire 有效时间 0为永久
   * @return {boolean}
   */
  set(key, value, expire = null) {
    try {
      if (expire === null) {
        expire = config.expire
      }

      if (expire !== 0) {
        if (expire instanceof Date) {
          expire = expire.getTime()
        } else {
          expire = Date.now() + expire
        }
      }
      uni.setStorageSync(this.getKey(key), {
        expire,
        value
      })
      return true
    } catch {
      return false
    }
  }

  /**
   * 获取缓存
   * @param {string} key 缓存标识
   * @param {any} $default 默认值
   * @return {any}
   */
  get(key, $default = null) {
    try {
      if (this.has(key)) {
        const data  = uni.getStorageSync(this.getKey(key))
        if (!data) {
          return $default
        }
        
        const {value, expire} = data
        if (expire && expire < Date.now()) {
          this.remove(key)
          return $default
        }
        
        return value
      }
    } catch {
      return $default
    }
    return $default
  }

  /**
   * 从本地缓存中同步移除指定 key
   * @param {string} key 缓存标识
   * @return {boolean}
   */
  remove(key) {
    try {
      if (this.has(key)) {
        uni.removeStorageSync(this.getKey(key))
      }
      return true
    } catch {
      return false
    }
  }

  /**
   * 检测缓存 key 是否存在
   * @param {string} key 缓存标识
   * @return {boolean}
   */
  has(key) {
    return uni.getStorageInfoSync().keys.includes(this.getKey(key))
  }

  /**
   * 清空缓存
   * @return {boolean}
   */
  clear() {
    try {
      uni.clearStorageSync()
      return true
    } catch {
      return false
    }
  }

  /**
   * 获取缓存键名
   * @param {string} key
   * @return {string}
   */
  getKey(key) {
    return config.prefix + String(key)
  }
}

export default new Cache()
